package com.lzw.service.impl.admin;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.lzw.mapper.admin.StudentManagementMapper;
import com.lzw.pojo.Student;
import com.lzw.service.admin.StudentManagementService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class StudentManagementImpl implements StudentManagementService {

    @Autowired
    private StudentManagementMapper studentManagementMapper;

    @Override
    public List<Student> listStudents(Integer pageNum, Integer pageSize, String name, String gender, String phone) {
        PageHelper.startPage(pageNum,pageSize);
        List<Student> list = studentManagementMapper.listStudents(name, gender, phone);
        Page<Student> students = (Page<Student>) list;
        return students;
    }

    @Override
    public void deleteStudent(List<Integer> ids) {
        studentManagementMapper.deleteStudent(ids);
    }

    @Override
    public Student getStudentById(int id) {
        return studentManagementMapper.getStudentById(id);
    }

    @Override
    public void addStudent(Student student) {
        // 检查姓名是否存在
        if (studentManagementMapper.countByName(student.getName()) > 0){
            throw new IllegalArgumentException("学生姓名已存在");
        }

        // 检查用户名是否存在
        if (studentManagementMapper.countByUsername(student.getUsername()) > 0){
            throw new IllegalArgumentException("学生用户名已存在");
        }

        // 检查电话是否存在
        if (studentManagementMapper.countByPhone(student.getPhone()) > 0){
            throw new IllegalArgumentException("学生联系电话已存在");
        }

        studentManagementMapper.addStudent(student);
    }

    @Override
    public void updateStudent(Student student) {
        Student existing = studentManagementMapper.getStudentById(student.getStudentId());

        //检查学生是否存在
        if (existing == null){
            throw new IllegalArgumentException("学生不存在");
        }

        // 检查姓名重复
        if (!existing.getName().equals(student.getName())
                && studentManagementMapper.countByName(student.getName()) > 0){
            throw new IllegalArgumentException("学生姓名重复");
        }

        // 检查用户名重复
        if (!existing.getUsername().equals(student.getUsername())
                && studentManagementMapper.countByUsername(student.getUsername()) > 0){
            throw new IllegalArgumentException("学生用户名重复");
        }

        // 检查电话重复
        if (!existing.getPhone().equals(student.getPhone())
                && studentManagementMapper.countByPhone(student.getPhone()) > 0){
            throw new IllegalArgumentException("学生联系电话重复");
        }

        studentManagementMapper.updateStudent(student);
    }
}
